<?php

namespace App\Http\Controllers;

use App\Models\PhonePasswordReset;
use App\Models\User;
use App\Rules\CheckMobile;
use App\Rules\SecuriytCode;
use Carbon\Carbon;
use Illuminate\Auth\Passwords\TokenRepositoryInterface;
use Illuminate\Http\Request;
use App\Http\Controllers\Home\PaymentNotifyController;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Validator;
use Payment\Client\Notify;
use Payment\Common\PayException;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('home');
    }

    /**
     * @desc 找回密码
     */
    public function getFindPwd(Request $request)
    {
        return view('home.findpwd1');
    }

    /**
     * @param Request $request
     * @return $this|\Illuminate\Http\RedirectResponse
     * 提交账号验证信息
     */
    public function postVerifyAccount(Request $request)
    {
        $data = $request->all();
        $message = [
            'code.required' => '请输入验证码',
            'code.captcha' => '验证码错误'
        ];
        $validator = Validator::make($data, [
            'code' => 'required|captcha',
        ], $message);

        if ($validator->fails())
            return redirect()->back()->withErrors($validator)->withInput();

        $validator = Validator::make($data, [
            'name' => 'required|exists:users,name|min:6|max:20'
        ], [
            'name.required' => '请输入用户名',
            'name.min' => '用户名长度错误',
            'name.max' => '用户名长度错误',
            'name.exists' => '该用户不存在'
        ]);

        if ($validator->fails())
            return redirect()->back()->withErrors($validator)->withInput();

        $request->session()->put('user.account', $data['name']);

        return redirect()->route('getVerifyMobile');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     * 获取验证手机号码页面
     */
    public function getVerifyMobile(Request $request)
    {

//        if (!$request->session()->has('user.account'))
//            return redirect()->route('getVerifyAccount');

        return view('home.findpwd2');
    }

    /**
     * @param Request $request
     * @return $this|\Illuminate\Http\RedirectResponse
     * 验证手机号码
     */
    public function postVerifyMobile(Request $request)
    {
        $data = $request->all();
//        $name = $request->session()->get('user.account');
        $message = [
            'telephone.required' => '请输入手机号码',
            'telephone.exists' => '所输入号码与用户名不匹配',
            'code.required' => '请输入短信验证码'
        ];
        $validator = Validator::make($data, [
            'telephone' => ['required', new CheckMobile(),
//                Rule::exists('users')->where(function ($query) use($name) {
//                    $query->where('name', $name);
//                })
            ],
//            'code' => ['required',new SecuriytCode($data['telephone'])]
        ], $message);

        if ($validator->fails())
            return redirect()->back()->withErrors($validator)->withInput();
        $now = Carbon::now()->toDateTimeString();
        $token = md5(str_random(64) . $data['telephone'] . $now . 'salt');
        $resetToken = new PhonePasswordReset();
        $resetToken->phone = $data['telephone'];
        $resetToken->token = $token;
        $resetToken->created_at = $now;
        $resetToken->save();

        $request->session()->put('user.telephone', $data['telephone']);
        $request->session()->put('user.token', Hash::make($token));
        return redirect()->route('getReset');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     * 获取重置密码页面
     */
    public function getReset(Request $request)
    {
//        $name = $request->session()->get('user.account');
        $telephone = $request->session()->get('user.telephone');
        $token = $request->session()->get('user.token');

        if (empty($telephone) || empty($token))
            return redirect()->route('getVerifyMobile');

        $resetToken = PhonePasswordReset::select('id', 'phone', 'token', 'created_at')
            ->where('phone', $telephone)
            ->orderBy('id', 'desc')
            ->first();

        if (!$resetToken)
            return redirect()->route('getVerifyMobile');

        if (!Hash::check($resetToken->token, $token))
            return redirect()->route('getVerifyMobile');

        return view('home.findpwd3');
    }

    /**
     * @param Request $request
     * @return $this|\Illuminate\Http\RedirectResponse
     * 重置密码
     */
    public function postReset(Request $request)
    {
        $data = $request->all();

        $message = [
            'password.required' => '请输入密码',
            'password.string' => '数据格式错误',
            'password.min' => '密码不能小于6位',
            'password.max' => '密码不能大于20位',
            'password.confirmed' => '两次输入的密码不一致',
        ];

        $validator = Validator::make($data, [
            'password' => 'required|string|min:6|max:20|confirmed',
        ], $message);

        if ($validator->fails())
            return redirect()->back()->withErrors($validator)->withInput();

//        $name = $request->session()->get('user.account');
        $telephone = $request->session()->get('user.telephone');
        $token = $request->session()->get('user.token');

        if (empty($token) || empty($telephone))
            return redirect()->route('getVerifyMobile');

        $resetToken = PhonePasswordReset::select('id', 'phone', 'token', 'created_at')
            ->where('phone', $telephone)
            ->orderBy('id', 'desc')
            ->first();

        if (!$resetToken)
            return redirect()->route('getVerifyMobile');

        if (!Hash::check($resetToken->token, $token))
            return redirect()->route('getVerifyMobile');

        $diff = Carbon::now()->diffInMinutes(Carbon::parse($resetToken->created_at));

        if ($diff > 30)
            return redirect()->route('getVerifyMobile');

        $user = User::select('id', 'name', 'telephone')
            ->where('telephone', $telephone)
            ->first();

        if (!$user)
            return redirect()->route('getVerifyMobile');

        $user->password = Hash::make($data['password']);
        $user->save();

        $request->session()->flash('resetPasswordDone', true);
//        $request->session()->flash('user', ['account' => $name, 'telephone' => $telephone]);

        return redirect()->route('getResetPwdDone');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     * 获取修改完成页面
     */
    public function getResetPwdDone(Request $request)
    {
        if (!$request->session()->has('resetPasswordDone') || !$request->session()->exists('user'))
            return redirect()->route('getVerifyMobile');

        $request->session()->forget('user');
        $request->session()->forget('resetPasswordDone');

        return view('home.findpwd4');
    }

    /**
     * @desc 错误页面
     */
    public function pageError()
    {
    	return view('pageError');
    }
    
    /**
     * 支付宝异步通知
     */
    public function notify(Request $request)
    {
    	
    	
    }
}
